<template>
    <div>
        <!--    面包屑导航区-->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>撰写博客</el-breadcrumb-item>
        </el-breadcrumb>

        <el-row :gutter="5">
            <h4>文章标题</h4>
            <el-col :span="16" :offset="4">
                <el-input placeholder="请输入文章标题" v-model="blog.title"></el-input>
            </el-col>
        </el-row>

        <el-row>
            <h4>文章描述</h4>
            <el-col :span="20" :offset="2">
                <el-input placeholder="请输入文章描述" v-model="blog.description"></el-input>
            </el-col>
        </el-row>

        <!-- 文本输入区 -->
        <el-row>
            <mavon-editor
                    ref="markdownEditor"
                    @imgAdd="imgAdd"
                    @imgDel="imgDel"
                    :ishljs="true"
                    v-model="blog.content"
                    style="margin: 10px auto;min-height: 70vh"
            />
        </el-row>
        <!-- markdown 即时渲染区 -->
        <el-row align="right" type="flex" justify="end">
        </el-row>

        <el-button style="border-radius: 20px;
                          position: fixed;
                          left: 14%;
                          bottom: 50px;
                          z-index: 9999"
                   type="danger"
                   v-if="!publishDialogFormVisible"
                   @click="submit">
            发布文章
        </el-button>

        <!-- 点击发布时，弹出选填信息窗口 -->
        <el-dialog class="publish_dialog" title="发布文章" :visible.sync="publishDialogFormVisible">

            <el-form style="text-align: left" ref="publishFormRef" :model="publishForm" :rules="publishFormRules"
                     class="publish_form">

                <el-form-item label="文章分类" prop="type">
                    <el-select size="small" v-model="publishForm.type" placeholder="请选择文章分类" style="margin-right: 10px"
                               @change="setBlogType">
                        <el-option v-for="type in typeList" :label="type.name" :value="type.id" :key="type.id"></el-option>
                    </el-select>
                    <!--<el-button size="small" @click="addNewType">+ 新建分类</el-button>-->
                </el-form-item>

                <el-form-item label="文章标签" prop="tags">
                    <el-card shadow="never" style="height: 120px; overflow: auto">
                        <el-checkbox-group v-model="publishForm.tags">
                            <el-checkbox v-for="tag in tagList" :label="tag.id" :key="tag.id">{{tag.name}}</el-checkbox>
                        </el-checkbox-group>
                        <!--<el-button size="mini" @click="addNewTag">+ 新建标签</el-button>-->
                    </el-card>
                </el-form-item>

                <el-form-item label="文章类型" prop="flag">
                    <el-select size="small" v-model="publishForm.flag">
                        <el-option
                                v-for="item in flags"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="文章首图">
                    <!-- 图片上传区 -->
                    <el-upload
                            ref="upload"
                            action="#"
                            :http-request="uploadImg"
                            list-type="picture-card"
                            :limit="1"
                            :show-file-list="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="handleSuccess">
                        <!-- 小图预览 -->
                        <img v-if="dialogImageUrl" :src="dialogImageUrl" class="preview">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <!-- 大图预览 -->
                    <el-dialog :visible.sync="dialogVisible" :modal="false" style="top: auto" :before-close="reSelect">
                        <img width="100%" :src="dialogImageUrl" alt="">
                        <el-button type="primary" @click="reSelect">重新选择</el-button>
                        <el-button type="success" @click="confirmSelect">确定</el-button>
                    </el-dialog>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="backPage">取消</el-button>
                <el-button type="primary"
                           @click="publishBlog"
                >
                    发布文章
                </el-button>
            </div>
        </el-dialog>
    </div>

</template>

<script>
export default {
    data() {
        return {
            blog: {
                id:null,
                userId:null,
                typeId:null,
                title: "",
                description:"",
                content: "",
                flag: "",
                firstPicture: "",
                appreciation: 0,
                views: 0,
                commentabled: false
            },
            dialogImageUrl:'',
            flags: [
                {value: "原创", label: "原创"},
                {value: "转载", label: "转载"}
            ],
            publishDialogFormVisible: false,
            publishForm: {
                // type: {},
                tags: [],
                flag:'原创' //默认是原创
            },
            typeList: [],
            tagList: [],
            publishFormRules: {
                type:[
                    {required: true,message: '请选择类型',trigger: 'blur'}
                ],
                tags:[
                    {required: true,message: '请选择至少一种标签',trigger: 'blur'}
                ],
                flag:[
                    {required: true,message: '请选择文章类型',trigger: 'blur'}
                ],
            },
            dialogVisible: false
        }
    },
    created(){
      if (typeof this.$route.query.blog !== 'undefined'){
          this.blog = JSON.parse(this.$route.query.blog)
          //数据库过来的，是 md 格式的文本
      }
    },
    methods: {
        //确认选择图片
        confirmSelect(){
            this.dialogVisible=false;
        },
        //重新选择图片
        reSelect(){
            this.dialogImageUrl=null;
            this.dialogVisible=false;
        },
        // 获取博客类型列表
        async getTypeList() {
            const {data: res} = await this.$basic.get('/type/allTypes')
            this.typeList = res.data.typeList
        },
        // 获取博客标签列表
        async getTagList() {
            const {data: res} = await this.$basic.get('/tag/allTags')
            this.tagList = res.data.tagList
        },
        async submit() {
            if (this.blog.id!==null){
                const {data: res} = await this.$admin.post('/addNewBlog',this.blog)
                // console.log(res)
                if (res.code === 200) {
                    this.publishDialogFormVisible = false
                    this.$router.go(-1);
                    return this.$message.success('修改博客成功！')
                } else {
                    this.publishDialogFormVisible = false
                    return this.$message.error('修改博客失败！')
                }

            } else {
                await this.getTypeList()
                await this.getTagList()
                this.publishDialogFormVisible = true
            }
        },
        //获得一二级标题导航
        getNavList(content){
            //console.log(content);
        },

        async handleSuccess(res) {
            this.$refs.upload.clearFiles();
            this.dialogVisible = true
        },

        async addNewType(){
            console.log("待添加功能")
        },

        async addNewTag(){
            console.log("待添加功能")
        },

        publishBlog() {
            this.$refs.publishFormRef.validate( async valid => {
                if (!valid) return
                //设置将传给后端的 blog 对象
                this.blog.firstPicture = this.dialogImageUrl
                this.blog.flag = this.publishForm.flag
                this.blog.userId = (JSON.parse(window.sessionStorage.getItem('user'))).id
                /*
                this.tempContent = this.blog.content
                this.blog.content = this.$refs.markdownEditor.d_render
                */

                const {data : res} = await  this.$admin.post('/addNewBlog',this.blog)
                //this.blog.content = this.tempContent
                //console.log(res)
                // 再绑定所选的标签
                let newBt = {};
                let tagIds = this.publishForm.tags
                for(let i=0;i<tagIds.length;i++){
                    newBt.blogsId = res.data.id;
                    newBt.tagsId = tagIds[i];
                    let {data:res1} = await this.$basic.post('/blogTags/addNewBt',newBt)
                    //console.log(res1)
                }
                if (res.code === 200) {
                    this.publishDialogFormVisible = false
                    await this.$router.push('/admin/blogs')
                    await location.reload();
                    return this.$message.success('发布博客成功！')
                } else {
                    this.publishDialogFormVisible = false
                    return this.$message.error('发布博客失败！')
                }
            })
        },

        async uploadImg(val){
            let fd = new FormData();
            fd.append('myfile',val.file)
            const{data:res} = await this.$basic.post('/upload',fd)
            let picName = res.data
            this.dialogImageUrl = 'http://localhost:8888/yumWebsite/avatar/'+picName
        },

        /**
         * 添加图片事件
         */
        async imgAdd(pos,file) {
            let fd = new FormData();
            fd.append('myfile',file);
            const{data:res} = await this.$basic.post('/upload',fd)
            let picName = res.data
            // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
            const markdown = this.$refs.markdownEditor;
            markdown.$img2Url(pos, 'http://localhost:8888/yumWebsite/avatar/'+picName);
        },
        /**
         * 图片删除
         */
        imgDel(pos) {
            delete this.img_file[pos];
        },

        handleRemove() {
            this.dialogImageUrl = ''
            // console.log(file, fileList);
        },

        handlePictureCardPreview(file) {
            //console.log(file)
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        setBlogType(res) {
            //console.log(res)
            this.blog.typeId = (this.typeList.find(item => item.id === res)).id
        },

        backPage(){
            this.$refs.upload.clearFiles()
            this.blog.firstPicture = ''
            this.publishDialogFormVisible = false
            this.$refs.publishFormRef.resetFields()
        }
    }
}
</script>

<style scoped lang="less">
    .el-form /deep/ .el-form-item__content {
        line-height: 23px;
    }

    .el-card /deep/ .el-card__body {
        padding: 10px;
    }

    .publish_dialog{
        //自适应
        top: auto;
    }

    .publish_form{

    }

    .preview {
        width: 100%;
        height: 100%;
        display: block;
    }
</style>
